package lesson02;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class TestMain9 {

	public static void main(String[] args) {
		Set<String> set = new HashSet();
		set.add("bbbb");
		set.add("aaaa");
		set.add("cccc");
		System.out.println(set.add(new String("aaaa"))); // 去重
		System.out.println(set.size());
		set.forEach(System.out::println);
		
		// HashSet如何判定重复: hashcode和equals 可以自定义
		Set<Student> sset = new HashSet<>();
		sset.add(new Student("tom", 10));
		sset.add(new Student("jerry", 10));
		sset.add(new Student("tom", 10));
		sset.add(new Student("tom", 11));
		System.out.println(sset.size()); // 3
		sset.forEach(System.out::println);
		
		// TreeSet如何判定重复:  Comparable接口中的  compareTo的返回值
		Set<Student> tset = new TreeSet<>();
		tset.add(new Student("tom", 10));
		tset.add(new Student("jerry", 10));
		tset.add(new Student("tom1", 10));
		tset.add(new Student("tom2", 14));
		tset.add(new Student("tom3", 11));
		tset.add(new Student("tom4", 12));
		tset.add(new Student("tom5", 11));
		System.out.println(tset.size()); // 3
		tset.forEach(System.out::println);
		
		
		List<Student> tslist = new ArrayList<>();
		tslist.add(new Student("tom", 10));
		tslist.add(new Student("jerry", 10));
		tslist.add(new Student("tom1", 10));
		tslist.add(new Student("tom2", 14));
		tslist.add(new Student("tom3", 11));
		tslist.add(new Student("tom4", 12));
		tslist.add(new Student("tom5", 11));
		System.out.println(tslist.size()); // 3
		tslist.forEach(System.out::println);
		
		// 实际应用
		System.out.println("--------------");
		
		// 自然排序
		Collections.sort(tslist);
		
		// 比较器
		Collections.sort(tslist, (o1, o2) -> {
			// 前-后  升序，  后-前降序
			return o2.getAge() - o1.getAge();
		});
		tslist.forEach(System.out::println);
	}
}
// Comparable自然排序
class Student implements Comparable<Student> {
	private String name;
	private int age;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public int hashCode() {
		return name.hashCode();
	}
	@Override
	public boolean equals(Object obj) {
		return this.name.equals(((Student)obj).name);
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	/*
	 * 返回值： 负数   是 大于
	 *       0  相等
	 *       正     是小于
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@Override
	public int compareTo(Student o) {
			
		// this.age - o.age;
		return this.name.compareTo(o.name);
	}
	
}
